package chances.epg.api.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import chances.epg.api.controller.model.ResultResponse;
import chances.epg.commons.log.EpgLogFactory;
import chances.epg.data.service.BizService;
import chances.epg.entity.biz.Biz;

@RestController
public class BizDataController extends AbstractDataController {
	private static Logger logger = EpgLogFactory.getSystemLogger();

	@Autowired
	private BizService bizService;

	@RequestMapping(value = "/biz/{bizCode}")
	public ResultResponse<Biz> getBiz(@PathVariable String bizCode, ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Biz biz = null;
		int result = SUCCESS;

		try {
			biz = bizService.getBizByCode(bizCode);
			if (biz == null) {
				result = OBJ_NOT_FOUND;
			}

		} catch (DataAccessException ex) {
			result = DB_ERROR;
			logger.error(ex.getMessage(), ex);
		} catch (Throwable ex) {
			result = ERROR;
			logger.error(ex.getMessage(), ex);
		}
		return new ResultResponse<Biz>(result, biz);
	}

	@RequestMapping(value = "/bizlist/{bizCode}")
	public ResultResponse<List<Biz>> getBizList(@PathVariable String bizCode, ModelMap model,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<Biz> bizList = null;
		int result = SUCCESS;

		try {
			bizList = bizService.getChildrenOfBiz(bizCode);
		} catch (DataAccessException ex) {
			result = DB_ERROR;
			logger.error(ex.getMessage(), ex);
		} catch (Throwable ex) {
			result = ERROR;
			logger.error(ex.getMessage(), ex);
		}
		return new ResultResponse<List<Biz>>(result, bizList);

	}
}
